package com.example.task1.ui.poverty;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;

import com.example.task1.R;
import com.example.task1.application.MyApplication;
import com.example.task1.http.Api;
import com.example.task1.util.ApiResp;
import com.example.task1.util.CallBack;

import java.io.File;

import retrofit2.Call;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link PovertyFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class PovertyFragment extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private Button btnUpFile;
    private Button btnSave;
    private Uri mSelectedImageUri;
    private final static int PERMISSION_REQUEST_CODE = 1;
    private final static int PICK_IMAGE = 1;

    public PovertyFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment PovertyFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static PovertyFragment newInstance(String param1, String param2) {
        PovertyFragment fragment = new PovertyFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_poverty, container, false);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (requestCode == 1 && resultCode == Activity.RESULT_OK & data != null) {
            mSelectedImageUri = data.getData();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1 && permissions[0] == Manifest.permission.READ_EXTERNAL_STORAGE && grantResults[0] == Activity.RESULT_OK) {
            Intent intent = new Intent(Intent.ACTION_ATTACH_DATA);
            //指定获取的是图片
            intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
            startActivityForResult(intent, PICK_IMAGE);
        }
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView(view);
        btnSave.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("WrongConstant")
            @Override
            public void onClick(View v) {
                if (getContext().checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                    Intent intent = new Intent(Intent.ACTION_PICK);
                    //指定获取的是图片
                    intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                    startActivityForResult(intent, PICK_IMAGE);
                } else {
                    getActivity().requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
                }


            }
        });
        btnUpFile.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mSelectedImageUri != null) {
                    // 获取选中的图片文件路径
                    File filePath = getRealPathFromURI(mSelectedImageUri);
//                    File filePath =new File(mSelectedImageUri.getPath());
                    // 将选中的图片上传到服务器
                    Call<ApiResp> post = Api.api().post(MyApplication.TOKEN, "/prod-api/common/upload", Api.getFileBody(filePath));
                    Api.send(post, ApiResp.class, new CallBack<ApiResp>() {
                        @Override
                        public void success(ApiResp data) {
                            System.out.println();
                        }

                        @Override
                        public void error(String msg) {

                        }
                    });
                }
            }
        });
    }


    private File getRealPathFromURI(Uri uri) {
        String[] projection = {MediaStore.Images.Media.DATA};
        Cursor cursor = getActivity().getContentResolver().query(uri, new String[]{MediaStore.Images.Media.DATA}, null, null, null);
        if (cursor != null) {
            int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            String filePath = cursor.getString(columnIndex);
            cursor.close();
            return new File(filePath);
        } else {
            return null;
        }
    }

    private void initView(View view) {
        btnUpFile = view.findViewById(R.id.btn_upFile);
        btnSave = view.findViewById(R.id.btn_save);
    }
}